package com.newland.mesdk.demo.main;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import com.newland.mesdk.demo.main.R;
import com.newland.mtype.module.common.swiper.SwipResult;
import com.newland.mtype.util.ISOUtils;
import com.newland.mesdk.demo.activity.BaseActivity;
import com.newland.mesdk.demo.activity.N900KeyBoardNumberActivity;
import com.newland.mesdk.demo.device.AudioDevice;
import com.newland.mesdk.demo.device.BlueToothDevice;
import com.newland.mesdk.demo.device.K21Device;
import com.newland.mesdk.demo.device.USBDevice;
import com.newland.mesdk.demo.fragment.MenuFragment;
import com.newland.mesdk.demo.util.Const;
import com.newland.mesdk.demo.util.SharedPreferencesUtil;
import com.newland.mesdk.demo.util.Const.MessageTag;

/**
 * 主页面
 * 
 * @author YJF
 * 
 */

public class MainActivity extends BaseActivity {
	private Boolean isExit;
	private PopupWindow popupWindow;
	private int FLAG = -1;
	private byte[] pin;
	private SwipResult swipRslt;
	private static Handler pinHandler;
	private FragmentManager fm;
	private static BlueToothDevice blueTooth;
	private static K21Device k21Device;
	private static AudioDevice audioDevice;
	private static USBDevice usbDevice;
	private Button btn_sure, btn_cancel, btn_init, btn_delet, btn_clear;
	private ImageButton btnOperate;
	private Dialog dialogInit;
	private RadioButton btnBlueTooth, btnK21, btnAudio, btnUSB;

	public static AudioDevice getAudioDevice() {
		return audioDevice;
	}

	public static void setAudioDevice(AudioDevice audioDevice) {
		MainActivity.audioDevice = audioDevice;
	}

	public static K21Device getK21Device() {
		return k21Device;
	}

	public static void setK21Device(K21Device k21Device) {
		MainActivity.k21Device = k21Device;
	}

	public static BlueToothDevice getBlueTooth() {
		return blueTooth;
	}

	public static void setBlueTooth(BlueToothDevice blueTooth) {
		MainActivity.blueTooth = blueTooth;
	}

	public static USBDevice getUsbDevice() {
		return usbDevice;
	}

	public static void setUsbDevice(USBDevice usbDevice) {
		MainActivity.usbDevice = usbDevice;
	}

	public static Handler getPinHandler() {
		return pinHandler;
	}

	public static void setPinHandler(Handler pinHandler) {
		MainActivity.pinHandler = pinHandler;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		btn_init = (Button) findViewById(R.id.btn_init);
		btn_delet = (Button) findViewById(R.id.btn_delet);
		btn_clear = (Button) findViewById(R.id.btn_clear);
		btnOperate = (ImageButton) findViewById(R.id.btn_operate);
		blueTooth = new BlueToothDevice(this);
		k21Device = new K21Device(this);
		audioDevice = new AudioDevice(this);
		usbDevice = new USBDevice(this);
		initView();
		isExit = false;
		switchFragment(R.id.frame, new MenuFragment());
		isMenuFragment();
		pinHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				swipRslt = ((MyApplication) ((MainActivity.this).getApplication())).getSwipResult();
				switch (msg.what) {
				case 0: {
					String accNo = ((MyApplication) MainActivity.this.getApplication()).getIcCardNum();
					Intent intent = new Intent(MainActivity.this, N900KeyBoardNumberActivity.class);
					intent.putExtra("accNo", accNo);
					startActivityForResult(intent, 002);
					break;
				}

				case 1: {
					if (swipRslt == null) {
						showMessage("请先到刷卡模块，刷卡" + "\r\n", MessageTag.ERROR);
						processingUnLock();
					} else {
						String accNo = swipRslt.getAccount().getAcctNo();
						if (accNo == null) {
							showMessage("accNo=null,请先到刷卡模块，刷卡" + "\r\n", MessageTag.ERROR);
							processingUnLock();
						} else {
							Intent intent = new Intent(MainActivity.this, N900KeyBoardNumberActivity.class);
							intent.putExtra("accNo", accNo);
							startActivityForResult(intent, 002);
						}
						processingUnLock();
					}
					break;
				}

				default:
					break;
				}
			}

		};
	}

	public void myclick(View v) {
		switch (v.getId()) {
		case R.id.btn_operate: {
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				return;
			} else {
				initPopupWindowView();
			}

			break;
		}
		case R.id.btn_init:
			initDevice();

			break;
		case R.id.btn_delet: {
			deltDevice();

			break;
		}
		case R.id.btn_clear: {
			clearMessage();
			break;
		}
		case R.id.radiobtn_device_me30: {
			SharedPreferencesUtil.setStringParam(getApplicationContext(), Const.DEVICETYPE, Const.DeviceName.ME30);
			btnK21.setVisibility(View.GONE);
			btnBlueTooth.setVisibility(View.VISIBLE);
			btnAudio.setVisibility(View.GONE);
			btnUSB.setVisibility(View.GONE);
			showMessage("选择了me30", Const.MessageTag.NORMAL);
			FLAG = 1;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.BLUETOOTH);
			btnBlueTooth.setChecked(true);
			break;
		}
		case R.id.radiobtn_device_audio: {
			SharedPreferencesUtil.setStringParam(getApplicationContext(), Const.DEVICETYPE, Const.DeviceName.AUDIO);
			btnK21.setVisibility(View.GONE);
			btnBlueTooth.setVisibility(View.GONE);
			btnUSB.setVisibility(View.GONE);
			btnAudio.setVisibility(View.VISIBLE);
			showMessage("选择了音频设备", Const.MessageTag.NORMAL);
			FLAG = 0;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.AUDIO);
			btnAudio.setChecked(true);
			break;
		}
		case R.id.radiobtn_device_me31: {
			SharedPreferencesUtil.setStringParam(getApplicationContext(), Const.DEVICETYPE, Const.DeviceName.ME31);
			btnK21.setVisibility(View.GONE);
			btnAudio.setVisibility(View.GONE);
			btnUSB.setVisibility(View.GONE);
			btnBlueTooth.setVisibility(View.VISIBLE);
			showMessage("选择了me31", Const.MessageTag.NORMAL);
			FLAG = 1;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.BLUETOOTH);
			btnBlueTooth.setChecked(true);
			break;
		}
		case R.id.radiobtn_device_im81: {
			SharedPreferencesUtil.setStringParam(getApplicationContext(), Const.DEVICETYPE, Const.DeviceName.IM81);
			btnBlueTooth.setVisibility(View.GONE);
			btnAudio.setVisibility(View.GONE);
			btnUSB.setVisibility(View.GONE);
			btnK21.setVisibility(View.VISIBLE);
			showMessage("选择了im81", Const.MessageTag.NORMAL);
			FLAG = 2;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.K21);
			btnK21.setChecked(true);
			break;
		}
		case R.id.radiobtn_device_n900: {
			SharedPreferencesUtil.setStringParam(getApplicationContext(), Const.DEVICETYPE, Const.DeviceName.N900);
			btnBlueTooth.setVisibility(View.GONE);
			btnAudio.setVisibility(View.GONE);
			btnUSB.setVisibility(View.GONE);
			btnK21.setVisibility(View.VISIBLE);
			showMessage("选择了n900", Const.MessageTag.NORMAL);
			FLAG = 2;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.K21);
			btnK21.setChecked(true);
			break;
		}
		case R.id.radiobtn_connect_audio: {
			FLAG = 0;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.AUDIO);

			break;
		}
		case R.id.radiobtn_connect_bluetooth: {
			FLAG = 1;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.BLUETOOTH);

			break;
		}
		case R.id.radiobtn_connect_k21: {
			FLAG = 2;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.K21);

			break;
		}
		case R.id.radiobtn_connect_usb: {
			FLAG = 3;
			SharedPreferencesUtil.setStringParam(getApplication(), Const.CONNECTTYPE, Const.ConnectTypeName.USB);

			break;
		}

		default:
			break;
		}

	}

	// 按返回键的监听，若当前页面为一级菜单页面，则退出应用程序，否则返回一级菜单页面
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() != KeyEvent.ACTION_UP) {
			isMenuFragment();
			if (!isExit) {
				switchFragment(R.id.frame, new MenuFragment());
			} else {
				if (FLAG == 0) {
					audioDevice.disconnect();
				} else if (FLAG == 1) {
					unregisterReceiver(blueTooth.getDiscoveryReciever());
					blueTooth.disconnect();
				} else if (FLAG == 2) {
					k21Device.disconnect();
				}
				finish();
			}

			return false;
		}
		return super.dispatchKeyEvent(event);
	}

	// 判断是否为一级菜单页面
	public void isMenuFragment() {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				fm = getFragmentManager();
				if (fm.findFragmentByTag("tag") instanceof MenuFragment) {
					isExit = true;
					btnOperate.setVisibility(View.VISIBLE);
					RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
							RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
					layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
					btn_clear.setLayoutParams(layoutParams);
					btn_clear.setVisibility(View.VISIBLE);
					btn_init.setVisibility(View.GONE);
					btn_delet.setVisibility(View.GONE);
				} else {
					isExit = false;
					btnOperate.setVisibility(View.GONE);
					btn_clear.setVisibility(View.GONE);
					btn_init.setVisibility(View.VISIBLE);
					btn_delet.setVisibility(View.VISIBLE);
				}
			}
		});

	}

	
	// N900密码输完返回
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 002) {
			if (resultCode == RESULT_OK) {
				pin = data.getByteArrayExtra("pin");
				Log.i("onActivityResult", "输入成功：" + ISOUtils.hexString(pin));
				showMessage("输入成功：" + ISOUtils.hexString(pin), MessageTag.DATA);
			} else if (resultCode == RESULT_CANCELED) {
				showMessage("N900KeyBoard取消密码输入" + "\r\n", MessageTag.TIP);
			}
		}
	}

	// 初始化POPWindow
	public void initPopupWindowView() {
		View popView = getLayoutInflater().inflate(R.layout.popview_item, null, false);

		DisplayMetrics dm = new DisplayMetrics();
		// 获取屏幕信息
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		int screenWidth = dm.widthPixels;

		int screenHeigh = dm.heightPixels;
		// 创建PopupWindow实例,宽度为屏幕1/3，高度为屏幕1/5
		popupWindow = new PopupWindow(popView, screenWidth / 3, screenHeigh / 5);
		popupWindow.setOutsideTouchable(true);
		int y = (findViewById(R.id.rel_title).getHeight()) / 2 - (findViewById(R.id.btn_operate).getHeight()) / 2;
		popupWindow.showAsDropDown(findViewById(R.id.btn_operate), 0, y);
		popView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					popupWindow = null;
				}
				return false;
			}
		});
		Button btnInitDevice = (Button) popView.findViewById(R.id.btn_pop_init);
		btnInitDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				initDevice();
				popupWindow.dismiss();
				isMenuFragment();
			}
		});
		Button btnDeltDevice = (Button) popView.findViewById(R.id.btn_pop_delet);
		btnDeltDevice.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				deltDevice();
				popupWindow.dismiss();
			}
		});

	}

	// 初始化设备
	public void initDevice() {
		final AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
		builder.setTitle("请选择连设备和接方式:");
		LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
		final View view = inflater.inflate(R.layout.dialog_initdevice, null);
		btn_sure = (Button) view.findViewById(R.id.btn_initdevice_sure);
		btn_cancel = (Button) view.findViewById(R.id.btn_initdevice_cancle);
		btnBlueTooth = (RadioButton) view.findViewById(R.id.radiobtn_connect_bluetooth);
		btnK21 = (RadioButton) view.findViewById(R.id.radiobtn_connect_k21);
		btnAudio = (RadioButton) view.findViewById(R.id.radiobtn_connect_audio);
		btnUSB = (RadioButton) view.findViewById(R.id.radiobtn_connect_usb);
		builder.setView(view);

		btn_sure.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				try {
					dialogInit.dismiss();
					switch (FLAG) {
					case 0:
						new Thread(new Runnable() {

							@Override
							public void run() {
								audioDevice.initController();
							}
						}).start();
						break;
					case 1: {
						blueTooth.startDiscovery();
						break;

					}
					case 2: {
						new Thread(new Runnable() {

							@Override
							public void run() {

								k21Device.initController();
							}
						}).start();
						break;
					}
					case 3: {
						new Thread(new Runnable() {

							@Override
							public void run() {
								usbDevice.initController();
							}
						}).start();
						break;
					}

					default:
						break;
					}
					switchFragment(R.id.frame, new MenuFragment());
				} catch (Exception e) {
					showMessage("初始化设备异常：" + e, MessageTag.ERROR);
				}
			}
		});

		btn_cancel.setOnClickListener(new android.view.View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				dialogInit.dismiss();
				switchFragment(R.id.frame, new MenuFragment());
			}
		});
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				dialogInit = builder.create();
				dialogInit.setCancelable(false);
				dialogInit.setCanceledOnTouchOutside(false);
				dialogInit.show();
			}
		});
	}

	// 删除设备
	public void deltDevice() {
		if (FLAG == 0) {
			audioDevice.disconnect();
			btnStateToWaitingInit();
		} else if (FLAG == 1) {
			blueTooth.disconnect();
			btnStateToWaitingInit();
		} else if (FLAG == 2) {
			k21Device.disconnect();
			btnStateToWaitingInit();
		} else if (FLAG == 3) {
			usbDevice.disconnect();
			btnStateToWaitingInit();
		} else {
			btnStateToWaitingInit();
		}
		processingUnLock();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (FLAG == 0) {
			audioDevice.disconnect();
		} else if (FLAG == 1) {
			blueTooth.disconnect();
		} else if (FLAG == 2) {
			k21Device.disconnect();
		}

	}

}
